package com.whyvent.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whyvent.common.lang.Result;
import com.whyvent.entity.MBlog;
import com.whyvent.service.IMBlogService;
import com.whyvent.utils.ShiroUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * @author WhyVent
 */

@RestController
public class BlogController {

    @Resource
    IMBlogService blogService;

    @GetMapping("/blogs")
    public Result list(@RequestParam(defaultValue = "1") Integer currentPage){

        Page page = new Page(currentPage,5);
        IPage pageData = blogService.page(page, new QueryWrapper<MBlog>().orderByDesc("created"));

        return Result.success(pageData);
    }
    @GetMapping("/blog/{id}")
    public Result detail(@PathVariable("id") Long id){
        MBlog blog = blogService.getById(id);
        Assert.notNull(blog,"博客不存在");

        return Result.success(blog);
    }

    @RequiresAuthentication
    @PostMapping("/blog/edit")
    public Result saveOrUpdate(@Validated @RequestBody MBlog blog){
        MBlog temp = null;
        if (blog.getId()!=null){ // 说明是编辑
            temp = blogService.getById(blog.getId());
            // 只能编辑自己的文章
            Assert.isTrue(temp.getUserId().equals(ShiroUtils.getProfile().getId()), "没有权限编辑");
        }else { // 说明是新建添加
            temp = new MBlog();
            temp.setUserId(blog.getUserId());
            temp.setCreated(LocalDateTime.now());
            temp.setStatus(0);
        }
        BeanUtil.copyProperties(blog,temp,"id","userId","created","status");
        blogService.saveOrUpdate(temp);
        return Result.success(temp);
    }
}
